<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <XForm :fieldList="fieldList" :options="formOption" :formData="form">
          <template #ShopCascade>
            <SelectsShopCascade v-model:platform="form.platform_id" v-model:site="form.site" v-model:shop="form.shop_id" />
          </template>
        </XForm>
      </template>
      <template #toolbar_btns>
        <VButton type="primary" @click="add" v-hasPermi="[basicSetupAuthList.profit_testing.add]">
          <div class="dk-iconfont icon-Plus"></div>
          新增
        </VButton>
        <VButton @click="handleStatus(1)" v-hasPermi="[basicSetupAuthList.profit_testing.enable]">
          <div class="dk-iconfont icon-CircleCheck text-[#3487FF]"></div>
          启用
        </VButton>
        <VButton @click="handleStatus(0)" v-hasPermi="[basicSetupAuthList.profit_testing.disable]">
          <div class="dk-iconfont icon-Disabled text-[red]"></div>
          禁用
        </VButton>
      </template>
    </VTable>

    <!-- 日志/ -->
    <Log dialog v-model="logVisible" :autoLoad="false" tag="profit_setting" :business_id="logId" />

    <Vedit ref="edit" :title="editTitle" class="dialogPublic" @confirm="editConfirm" :ruleTypeOption="ruleTypeOption" />
  </VPage>
</template>

<script setup lang="jsx" name="basic-setupProfit-testing">
import XForm from "@/components/XForm/index.vue"
import { overallOptions } from "@/api/public"
import { queryList, oplog, profitSettingDelete, setStatus } from "./api"

// 日志
import Log from "@/components/Log/index.vue"
const logRef = ref()
const logVisible = ref(false)
const logId = ref("")
const openLog = (row) => {
  logId.value = row.id
  logVisible.value = true
}
import { ElMessage, ElMessageBox } from "element-plus"
import Vedit from "./components/edit"
import { basicSetupAuthList } from "@/Auth/basic-setup.js"
import SelectsShopCascade from "@/components/Selects/SelectsShopCascade/index.vue"
import { onMounted, ref, toRefs } from "vue"

const edit = ref()
const data = reactive({
  editTitle: "新增",
  ruleTypeOption: [],
  statusOption: [],
})
const { editTitle, ruleTypeOption, statusOption } = toRefs(data)
const tableRef = ref()

const formOption = ref({
  inline: true,
})
const fieldList = ref([
  { slot: "ShopCascade" },
  {
    field: "create_user",
    type: "cascader",
    itemProps: { placeholder: "创建人" },
    style: { width: "200px" },
  },
  {
    field: "rule_name",
    placeholder: "规则名称",
    style: { width: "160px" },
  },
  {
    field: "rule_type",
    type: "select",
    options: {
      placeholder: "规则类型",
      data: ruleTypeOption,
    },
    style: { width: "180px" },
  },
])

//编辑
const ruleEdit = (row) => {
  editTitle.value = "编辑"
  edit.value.open(row)
}
//新增
const add = () => {
  editTitle.value = "新增"
  edit.value.open()
}
const editConfirm = () => {
  query()
}
//删除
const profitSettingDeleteF = (id) => {
  ElMessageBox.confirm("此操作将永久删除该项, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    confirmButtonClass: "oms-message-confirm-button",
  }).then(async () => {
    try {
      profitSettingDelete({ id }).then((res) => {
        ElMessage.success("删除成功")
        query()
      })
    } catch (e) {
      throw Error(e)
    }
  })
}

// 设置启用 禁用
const handleStatus = (status) => {
  if (!getSelectRow().length) {
    return false
  }
  const arr = getSelectRow()
  setStatus({ id: arr, status }).then((res) => {
    ElMessage({ message: "启用成功！", type: "success" })
    query()
  })
}

// 查询
const query = () => {
  tableRef?.value.query()
}

//获取下拉数据
onMounted(() => {
  overallOptions({ params: ["base.profitSetting"] }).then((res) => {
    ruleTypeOption.value = res.data.baseProfitSetting.rule_type
    statusOption.value = res.data.baseProfitSetting.status
  })
})
//获取已选中的行
const getSelectRow = () => {
  const getCheckboxRecords = tableRef?.value.$table.getCheckboxRecords()
  if (!getCheckboxRecords.length) {
    ElMessage({ showClose: true, message: "请至少选择一条数据！", type: "warning" })
    return false
  }
  const arr = []
  getCheckboxRecords.map((e) => {
    arr.push(e.id)
  })
  return arr
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      platform_id: "",
      site: [],
      shop: [],
      status: "",
      create_user: "",
      rule_type: "",
      rule_name: "",
    },
  },
  showOverflow: true,
  columns: [
    { type: "checkbox", fixed: "left", width: 60 },
    { field: "id", title: "ID", width: 100 },
    { field: "rule_name", title: "规则名称", width: 240 },
    {
      field: "rule_type",
      title: "规则类型",
      minWidth: 220,
      slots: {
        default: ({ row }) => {
          return <div>{row.rule_type == 1 ? "系统促销sku设置" : row.rule_type == 2 ? "按订单销售额区间设置" : "-"}</div>
        },
      },
    },
    {
      field: "currency",
      title: "销售币种类型",
      minWidth: 140,
      slots: {
        default: ({ row }) => {
          return <div>{row.currency || "-"}</div>
        },
      },
    },
    { field: "start_sell_price", title: "最低销售价", minWidth: 120 },
    { field: "close_sell_price", title: "最高销售价", minWidth: 140 },
    { field: "order_minimum", title: "订单利润率最低值", minWidth: 140 },
    {
      field: "sku",
      title: "策略SKU",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              {" "}
              {row.rule_type == 1 ? (
                <el-button type="primary" link onClick={() => showSKU(row.sku)}>
                  查看
                </el-button>
              ) : (
                <el-button type="info" disabled link>
                  查看
                </el-button>
              )}
            </div>
          )
        },
      },
    },
    {
      title: "状态",
      field: "status_text",
      width: 100,
      slots: {
        default: ({ row }) => <VStatus value={row.status == "1"} />,
      },
    },
    { field: "create_user", title: "创建人", width: 150 },
    { field: "create_time", title: "创建时间", width: 170 },
    {
      title: "操作",
      width: 150,
      fixed: "right",
      slots: {
        default: ({ row }) => {
          return [
            <div>
              <el-button link type="primary" onClick={() => ruleEdit(row)} v-hasPermi={[[basicSetupAuthList.profit_testing.edit]]}>
                编辑
              </el-button>
              <el-button link type="primary" onClick={() => openLog(row)} v-hasPermi={[[basicSetupAuthList.profit_testing.log]]}>
                日志
              </el-button>
              <el-button link type="danger" onClick={() => profitSettingDeleteF(row.id)} v-hasPermi={[[basicSetupAuthList.profit_testing.delete]]}>
                删除
              </el-button>
            </div>,
          ]
        },
      },
    },
  ],
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        let formData = { ...form, ...page }
        return queryList(formData)
      },
    },
  },
})

const handleCascadeChange = (value) => {
  const { platform_id, site, shop_id } = value
  const form = tableRef.value.getForm()
  tableRef.value.setForm({
    ...form,
    platform_id,
    site,
    shop_id,
  })
}

const showSKU = (sku) => {
  const message =
    sku.length &&
    sku.map((i) => {
      return h("p", null, i)
    })
  ElMessageBox({ title: "策略SKU", message: h("p", null, message) })
}
</script>
<style lang="scss" scoped></style>
